<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('班级表')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
        <a-button @click="updateStu()" type="primary" icon="plus">分配无班级学生</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
               <a-menu-item>
                <a @click="showDrawer(record.classId)">查看班级学生</a>
              </a-menu-item>
               <a-menu-item>
                <a @click="showModal(record.classId)">分配学员</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

          <cls-modal ref="modalForm" @ok="modalFormOk"></cls-modal>
          <!--整个抽屉-->
          <a-drawer
            title="博添实训"
            placement="right"
            :closable="true"
            :visible="visible"
            :after-visible-change="afterVisibleChange"
            :width="720"
            @close="onClose"
          >
            <template>

              <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-model-item label="学生姓名">
                  <a-input v-model="stuName" />
                  <a-button type="primary" @click="onSubmit(classId,stuName)" style="margin-right: 100px;position: relative;left: 400px;bottom:40px">
                    查询
                  </a-button>
                </a-form-model-item>
              </a-form-model>
              <a-table :columns="stuColumns" :data-source="stuList" bordered>
                  <template slot="classId" slot-scope="text">
                    {{text}}
                  </template>
                  <template slot="className" slot-scope="text">
                    {{text}}
                  </template>
                    <template slot="stuId" slot-scope="text">
                      {{text}}
                    </template>
                  <template slot="stuName" slot-scope="text">
                    {{text}}
                  </template>
              </a-table>

            </template>

          </a-drawer>

    <!--分配学员，穿梭框-->
    <a-modal v-model="stuVisible" title="博添实训" ok-text="确认" cancel-text="取消" @ok="hideModal" width='1000px'>
      <a-form-item label="模式选择">
        <a-radio-group  v-model="value">
          <a-radio :value="1" @click='noClassStu(classId)'>学生的分配</a-radio>
          <a-radio :value="2" @click='showModal(classId)'>修改学生班级</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-transfer
        :data-source="mockData"
        :target-keys="targetKeys"
        :disabled="disabled"
        show-search
        :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
        :show-select-all="false"
        @change="onChange"
      >
        <template
          slot="children"
          slot-scope="{
          props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
          on: { itemSelectAll, itemSelect },
        }"
        >
          <a-table
            :row-selection="
            getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
          "
            :columns="direction === 'left' ? leftColumns : rightColumns"
            :data-source="filteredItems"
            size="small"
            :style="{ pointerEvents: listDisabled ? 'none' : null }"
            :custom-row="
            ({ key, disabled: itemDisabled }) => ({
              on: {
                click: () => {
                  if (itemDisabled || listDisabled) return;
                  itemSelect(key, !selectedKeys.includes(key));
                },
              },
            })
          "
          />
        </template>
      </a-transfer>
    </a-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ClsModal from './modules/ClsModal'
  import {initDictOptions, filterDictText,filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import { httpAction, getAction, postAction } from '../../../api/manage'
  import difference from 'lodash/difference';
  import { message } from 'ant-design-vue';
  import { defineComponent, ref } from 'vue';
  const leftTableColumns = [
    {
      dataIndex: 'title',
      title: '学生编号',
    },
    {
      dataIndex: 'description',
      title: '学生姓名',
    },
   /* {
      dataIndex: 'classId',
      title: '班级编号',
    },*/
  ];
  const rightTableColumns = [
    {
      dataIndex: 'title',
      title: '当前班级学生编号',
    },
    {
      dataIndex: 'description',
      title: '当前班级学生姓名',
    }
  ];
  export default {
    name: 'ClsList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      ClsModal
    },
    data () {
      return {
        value: 2,
        mockData:[],
        targetKeys:[],
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
        description: '班级表管理页面',
        visible: false,
        stuVisible:false,
        /*mockData,*/
        /*targetKeys:originTargetKeys,*/
        disabled: false,
        showSearch: false,
        leftColumns: leftTableColumns,
        rightColumns: rightTableColumns,
        form: {
          stuName: '',
          region: undefined,
          date1: undefined,
          delivery: false,
          type: [],
          resource: '',
          desc: '',
        },
        //定义抽屉中的表头显示
        stuColumns:[
          {
            title: '班级编号',
            align: "center",
            dataIndex: 'classId'
          },
          {
            title: '班级名称',
            align: "center",
            dataIndex: 'className'
          },
          {
            title: '学生编号',
            align: "center",
            dataIndex: 'stuId'
          },
          {
            title: '学生真实姓名',
            align: "center",
            dataIndex: 'stuName'
          },
        ],
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function(t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '班级编号',
            align: "center",
            dataIndex: 'classId'
          },
          {
            title: '班级名称',
            align: "center",
            dataIndex: 'className'
          },
          {
            title: '开课时间',
            align: "center",
            dataIndex: 'curriculumTime'
          },
          {
            title: '班级状态',
            align: "center",
            dataIndex: 'classState',
            customRender: (text, record, index) => {
              //字典值替换通用方法
              return filterDictText(this.statesDictOptions, text);
            }
          },
          {
            title: '专业',
            align: "center",
            dataIndex: 'majorId',
            customRender: (text) => {
              for (let i = 0; i <this.majorIdDictOptions.length; i++) {
               if(text==this.majorIdDictOptions[i].majorId){
                 return this.majorIdDictOptions[i].majorName;
               }
              }
            }
          },
          {
            title: '班级阶段',
            align: "center",
            dataIndex: 'classStageId',
            customRender: (text) => {
              for (let i = 0; i <this.stageIdDictOptions.length; i++) {
                if(text==this.stageIdDictOptions[i].classStageId){
                  return this.stageIdDictOptions[i].classStageName;
                }
              }
            }
          },
          {
            title: '老师姓名',
            align: "center",
            dataIndex: 'teacherId',
            customRender: (text) => {
              for (let i = 0; i <this.teacherIdDictOptions.length; i++) {
                if(text==this.teacherIdDictOptions[i].teacherId){
                  return this.teacherIdDictOptions[i].teacherName;
                }
              }
            }

          },
          {
            title: '班级人数',
            align: "center",
            dataIndex: 'classNum'
          },
          {
            title: '课程',
            align: "center",
            dataIndex: 'courseId',
            customRender: (text) => {
              for (let i = 0; i <this.courseIdDictOptions.length; i++) {
                if(text==this.courseIdDictOptions[i].courseId){
                  return this.courseIdDictOptions[i].courseName;
                }
              }
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: { customRender: 'action' }
          }
        ],


        url: {
          list: "/cls/cls/list",
          delete: "/cls/cls/delete",
          deleteBatch: "/cls/cls/deleteBatch",
          exportXlsUrl: "/cls/cls/exportXls",
          importExcelUrl: "cls/cls/importExcel",
          majorIdUrl:"/major/major/list",
          stageIdUrl:"/classStage/classStage/list",
          courseIdUrl:"/course/course/list",
          teacherIdUrl:"/teacher/teacher/list",
          checkStuUrl:"/stumiddlecls/stuMiddleCls/Volist",
          CheckClsUrl:"/stumiddlecls/stuMiddleCls/CheckClsName",
          //修改学生的班级id
          updateStuClsIdUrl:"/cls/cls/updateStuClsId",
          //班级集合路径
          clsListUrl:"/cls/cls/getClsList",
          /*获取学生*/
          stuListUrl:"/stu/stu/getStuList",
          stuByClsListUrl:"/stumiddlecls/stuMiddleCls/getStuList",
          /*修改学生班级*/
          upStuListByClsUrl:"/stumiddlecls/stuMiddleCls/upStuListByCls",
          /*班级编号为0的学生查询*/
          selectClassIdEqNullUrl:"/stumiddlecls/stuMiddleCls/noClsIdStuList"
        },
        dictOptions: {},
        superFieldList: [],
        statesDictOptions: {},
        classStageIdDictOptions:[],
        majorIdDictOptions:[],
        stageIdDictOptions:[],
        courseIdDictOptions:[],
        teacherIdDictOptions:[],
        stuList:[],
        stuMiddleClsVo:{classId:''},
        stuName:null,
        classId:null,
        updateStuClsId:[],
        clsList:[],
        stuListByCls:[]
      }
    },
    created() {
      this.getSuperFieldList();
      this.getMajorIdList();
      this.getStageIdList();
      this.getCourseIdList();
      this.getTeacherIdList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      onChange(nextTargetKeys) {
        this.targetKeys = nextTargetKeys;
      },

      triggerDisable(disabled) {
        this.disabled = disabled;
      },

      triggerShowSearch(showSearch) {
        this.showSearch = showSearch;
      },
      getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
        return {
          getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
          onSelectAll(selected, selectedRows) {
            const treeSelectedKeys = selectedRows
              .filter(item => !item.disabled)
              .map(({ key }) => key);
            const diffKeys = selected
              ? difference(treeSelectedKeys, selectedKeys)
              : difference(selectedKeys, treeSelectedKeys);
            itemSelectAll(diffKeys, selected);
          },
          onSelect({ key }, selected) {
            itemSelect(key, selected);
          },
          selectedRowKeys: selectedKeys,
        };
      },

      noClassStu(classId){//查询没有班级编号的学生
        this.mockData=[]
        this.targetKeys=[]
        this.classId=classId
        /**获取班级编号为0的学生*//*班级为0和当前班级的总学生*/
         getAction(this.url.selectClassIdEqNullUrl+"/"+classId).then((resp)=>{
           if(resp.success){
             this.stuList=resp.result
             debugger
             for (let i = 0; i <this.stuList.length ; i++) {
               this.mockData.push({
                 key: this.stuList[i].stuId,//ID
                 title: this.stuList[i].stuId,//学生id
                 description: this.stuList[i].stuId,//描述要放学生的名字
               });
             }
           }
         })
        //调用方法，获得当前班级的学生
        this.getthisClassStu();
      },
      showModal(classId) {
        this.stuVisible = true;
        //初始化清空上一次push的数据
        this.mockData=[]
        this.targetKeys=[]
        //设置班级id
        this.classId=classId;

        /*获取所有学生*/
        getAction(this.url.stuListUrl).then((resp)=>{
          if (resp.success){
            this.stuList=resp.result
            for (let i = 0; i <this.stuList.length ; i++) {
              this.mockData.push({
                key: this.stuList[i].stuId,//ID
                title: this.stuList[i].stuId,//学生id
                description: this.stuList[i].stuName,//描述要放学生的名字
                classId:this.stuList[i].classId,//学生所属的班级(编号)
              });
            }
            /*this.targetKeys = this.mockData.filter(item => +item.classId==""||item.classId==classId).map(item => item.key);*/
          }
        })
        //调用方法，获得当前班级的学生
        this.getthisClassStu();
      },
      //获取当前班级的学生
      getthisClassStu(){
        /*获取选中班级的学生*/
        getAction(this.url.CheckClsUrl+"/"+this.classId).then((resp)=>{
          if (resp.success){
            this.stuListByCls=resp.result
            for (let i = 0; i <this.stuListByCls.length;i++) {
              this.targetKeys.push(this.stuListByCls[i].stuId)
            }
          }
        })
      },
      hideModal() {
        this.stuVisible = false;
        postAction(this.url.upStuListByClsUrl+"?classId="+this.classId,this.targetKeys).then((resp)=>{
          if (resp.success){
            message.success('修改成功');
          }else {
            message.warning('修改失败');
          }
        })
      },
      afterVisibleChange(val) {
        console.log('visible', val);
      },
      showDrawer(classId){
        this.visible = true;
        postAction(this.url.checkStuUrl+"/"+classId+"/"+null).then((res)=>{
          if (res.success){
            this.classId=classId
            this.stuList=res.result.records
          }
        })
      },
      onSubmit(classId,stuName) {
        postAction(this.url.checkStuUrl+"/"+classId+"/"+stuName).then((res)=>{
          if (res.success){
            this.stuList=res.result.records
          }
        })
      },

      onClose() {
        this.visible = false;
      },
      initDictConfig(){
        initDictOptions('class_status').then((res) => {
          if (res.success) {
            this.statesDictOptions = res.result;
          }
        });

      },
      //获取专业编号
      getMajorIdList(){
        httpAction(this.url.majorIdUrl,'','get').then((res)=>{
          if (res.success){
            this.majorIdDictOptions=res.result.records
          }
        })
      },
      //获取阶段id
      getStageIdList(){
        httpAction(this.url.stageIdUrl,'','get').then((res)=>{
          if (res.success){
            this.stageIdDictOptions=res.result.records
          }
        })
      },
      //获取老师id
      getTeacherIdList(){
        httpAction(this.url.teacherIdUrl,'','get').then((res)=>{
          if (res.success){
            this.teacherIdDictOptions=res.result.records
          }
        })
      },
      //获取课程id
      getCourseIdList(){
        httpAction(this.url.courseIdUrl,'','get').then((res)=>{
          if (res.success){
            this.courseIdDictOptions=res.result.records
          }
        })
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'classId',text:'班级编号',dictCode:''})
        fieldList.push({type:'string',value:'className',text:'班级名称',dictCode:''})
        fieldList.push({type:'datetime',value:'curriculumTime',text:'开课时间'})
        fieldList.push({type:'string',value:'classState',text:'班级状态',dictCode:'CLASS_STATES'})
        fieldList.push({type:'string',value:'majorId',text:'专业',dictCode:"major_id",dictTable:"major",dicText:"major_name" })
        fieldList.push({type:'string',value:'classStageId',text:'班级阶段',dictCode:"CLASS_STAGE,CLASS_STAGE_NAME,CLASS_STAGE_ID"})
        fieldList.push({type:'int',value:'classNum',text:'班级人数',dictCode:''})
        fieldList.push({type:'sel_search',value:'courseId',text:'课程',dictTable:"", dictText:'', dictCode:''})
        fieldList.push({type:'string',value:'teacherId',text:'老师',dictCode:"teacher_id",dictTable:"teacher",dicText:"teacher_name" })
        this.superFieldList = fieldList
      },
   },
  }

</script>

<style scoped>
  @import '~@assets/less/common.less';
</style>